
Partial Class LookupTables
    Inherits System.Web.UI.Page

    Const C_TABLE_NAMESPACE As String = ""

    Private message As String
    Private value As String
    Private index As Integer
    Private success As Integer

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load
        SetupJavaScript()
        ClearStatus()
        If Not Page.IsPostBack Then
            Me.LookupTablesScrollingGridView.Sort("Description", SortDirection.Ascending)
        End If

        Dim sType As String
        Dim sDataKey(0) As String
        sDataKey(0) = "Id"

        If Me.LuTablesDropDownList.SelectedValue.Equals("") Then
            sType = C_TABLE_NAMESPACE & "LuCaseStatus"
            Me.LookupTablesObjectDataSource.TypeName = sType
            Me.LookupTablesObjectDataSource.DataObjectTypeName = sType
        End If
        Me.LuTablesDropDownList.Attributes.Add("onchange", "document.getElementById(""mainSection"").style.visibility=""hidden""; document.getElementById(""addSection"").style.visibility=""hidden"";")

        sType = C_TABLE_NAMESPACE & Me.LuTablesDropDownList.SelectedValue
        Me.LookupTablesScrollingGridView.DataKeyNames = sDataKey
        'Me.RadGrid1.MasterTableView.DataKeyNames = sDataKey
        If Me.IsPostBack Then
            Me.LookupTablesObjectDataSource.DataObjectTypeName = sType
            Me.NewObjectDataSource.DataObjectTypeName = sType
            Me.NewObjectDataSource.TypeName = sType
            Me.LookupTablesObjectDataSource.TypeName = sType
        End If

    End Sub

    Private Sub SetupJavaScript()

        EntityController.JavaScriptAddChildDiv(Me.LookupTablesScrollingGridView.DivClientId, CInt(Me.LookupTablesScrollingGridView.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs", EntityController.JavaScriptScrollingGridStartup(Me.LookupTablesScrollingGridView), True)
        'EntityController.JavaScriptAddChilDiv(Me.PageDiv.ClientID, 38)
        'EntityController.JavaScriptAddChildDiv(Me.Panel1.ClientID, 100)
        EntityController.JavaScriptSetFixedHeight(28)
    End Sub

    Private Sub SetStatus(ByVal message As String)
        Me.LookupTablesScrollingGridView.StatusText = message
    End Sub

    Private Sub ClearStatus()
        SetStatus("")
    End Sub

    Private Sub SetGridViewPanelVisible(ByVal isVisible As Boolean)
        Me.LookupTablesScrollingGridView.Visible = isVisible
        Me.SubmitTableButton.Visible = isVisible
        Me.DropDownListsLabel.Visible = isVisible
        Me.LuTablesDropDownList.Visible = isVisible
    End Sub

    Protected Sub LuTablesDropDownList_SelectedIndexChanged(ByVal sender As Object, _
                                                     ByVal e As System.EventArgs) _
                                                     Handles LuTablesDropDownList.SelectedIndexChanged

        Me.ErrorSummary.Visible = False

        Dim lookupTableType As String = Me.LuTablesDropDownList.SelectedValue
        Me.LookupTablesObjectDataSource.TypeName = lookupTableType
        Me.NewObjectDataSource.TypeName = lookupTableType
        Me.LookupTablesObjectDataSource.DataObjectTypeName = lookupTableType
        Me.NewObjectDataSource.DataObjectTypeName = lookupTableType
        Me.NewObjectDataSource.Select()
        Me.LookupTablesObjectDataSource.Select()
        Me.NewDetailsView.DataBind()
        Me.LookupTablesScrollingGridView.DataBind()
        'Me.RadGrid1.DataBind()

    End Sub

    Protected Sub LookupTablesObjectDataSource_DataBinding(ByVal sender As Object, _
                                           ByVal e As System.EventArgs) _
                                           Handles LookupTablesObjectDataSource.DataBinding

        CheckMatch("LookupTablesObjectDataSource_DataBinding")

    End Sub

    Protected Sub LookupTablesObjectDataSource_ObjectCreating(ByVal sender As Object, _
                                              ByVal e As System.Web.UI.WebControls.ObjectDataSourceEventArgs) _
                                              Handles LookupTablesObjectDataSource.ObjectCreating

        CheckMatch("LookupTablesObjectDataSource_ObjectCreating")

    End Sub

    Protected Sub LookupTablesObjectDataSource_Selecting(ByVal sender As Object, _
                                         ByVal e As System.Web.UI.WebControls.ObjectDataSourceSelectingEventArgs) _
                                         Handles LookupTablesObjectDataSource.Selecting

        CheckMatch("LookupTablesObjectDataSource_Selecting")
        'Me.LookupTablesObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.LuTablesDropDownList.SelectedValue
        'Me.LookupTablesObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.LuTablesDropDownList.SelectedValue
        Me.LookupTablesObjectDataSource.TypeName = Me.LuTablesDropDownList.SelectedValue
        Me.LookupTablesObjectDataSource.DataObjectTypeName = Me.LuTablesDropDownList.SelectedValue

    End Sub

    Protected Sub LookupTablesObjectDataSource_Updating(ByVal sender As Object, _
                                        ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs) _
                                        Handles LookupTablesObjectDataSource.Updating

        CheckMatch("LookupTablesObjectDataSource_Updating")

    End Sub

    Protected Sub DoDelete(ByVal lookupType As String, ByVal id As Integer)

        Try

            Select Case lookupType

                Case "LuCaseStatus"

                    Dim caseStatus As Cdm.DataCore.LookupTables.LuCaseStatus
                    caseStatus = Cdm.DataCore.LookupTables.LuCaseStatus.Retrieve(id)
                    caseStatus.Remove()

                Case "LuMedicalSpecialty"

                    Dim medicalSpecialty As Cdm.DataCore.LookupTables.LuMedicalSpecialty
                    medicalSpecialty = Cdm.DataCore.LookupTables.LuMedicalSpecialty.Retrieve(id)
                    medicalSpecialty.Remove()

                Case "LuEmployeeServiceType"

                    Dim employeeServiceType As Cdm.DataCore.LookupTables.LuEmployeeServiceType
                    employeeServiceType = Cdm.DataCore.LookupTables.LuEmployeeServiceType.Retrieve(id)
                    employeeServiceType.Remove()

                Case "LuEmployeeAuthentication"

                    Dim employeeAuthentication As Cdm.DataCore.LookupTables.LuEmployeeAuthentication
                    employeeAuthentication = Cdm.DataCore.LookupTables.LuEmployeeAuthentication.Retrieve(id)
                    employeeAuthentication.Remove()

                Case "LuEmployeeType"

                    Dim employeeType As Cdm.DataCore.LookupTables.LuEmployeeType
                    employeeType = Cdm.DataCore.LookupTables.LuEmployeeType.Retrieve(id)
                    employeeType.Remove()

                Case "LuGeographicLocation"

                    Dim geographicLocation As Cdm.DataCore.LookupTables.LuGeographicLocation
                    geographicLocation = Cdm.DataCore.LookupTables.LuGeographicLocation.Retrieve(id)
                    geographicLocation.Remove()

                Case "LuLegalGuardianType"

                    Dim legalGuardianType As Cdm.DataCore.LookupTables.LuLegalGuardianType
                    legalGuardianType = Cdm.DataCore.LookupTables.LuLegalGuardianType.Retrieve(id)
                    legalGuardianType.Remove()

                Case "LuSourceOfEnrollment"

                    Dim sourceOfEnrollment As Cdm.DataCore.LookupTables.LuSourceOfEnrollment
                    sourceOfEnrollment = Cdm.DataCore.LookupTables.LuSourceOfEnrollment.Retrieve(id)
                    sourceOfEnrollment.Remove()

                Case "LuStatePlanOption"

                    Dim statePlanOption As Cdm.DataCore.LookupTables.LuStatePlanOption
                    statePlanOption = Cdm.DataCore.LookupTables.LuStatePlanOption.Retrieve(id)
                    statePlanOption.Remove()

                Case "LuCounty"

                    Dim county As Cdm.DataCore.LookupTables.LuCounty
                    county = Cdm.DataCore.LookupTables.LuCounty.Retrieve(id)
                    county.Remove()

                Case "LuRace"
                    Dim race As Cdm.DataCore.LookupTables.LuRace
                    race = Cdm.DataCore.LookupTables.LuRace.Retrieve(id)
                    race.Remove()
                Case "LuGender"
                    Dim gender As Cdm.DataCore.LookupTables.LuGender
                    gender = Cdm.DataCore.LookupTables.LuGender.Retrieve(id)
                    gender.Remove()
                Case "LuSpendingPlanDenialReason"
                    Dim denialReason As Cdm.DataCore.LookupTables.LuSpendingPlanDenialReason
                    denialReason = Cdm.DataCore.LookupTables.LuSpendingPlanDenialReason.Retrieve(id)
                    denialReason.Remove()
            End Select

            SetStatus("Item Deleted.")
        Catch ex As Gentle.Common.GentleException

            Me.ErrorSummary.Visible = True
            Me.ErrorSummary.SetSingleError("This item may not be deleted.  It is being used in the application.")
            Exit Sub

        End Try

    End Sub

    Private Function Exists(ByVal lookupType As String, ByVal description As String, ByVal id As Integer) As Boolean

        Try

            Select Case lookupType

                Case "LuCaseStatus"

                    Return Cdm.DataCore.LookupTables.LuCaseStatus.Exists(id, description)

                Case "LuMedicalSpecialty"

                    Return Cdm.DataCore.LookupTables.LuMedicalSpecialty.Exists(id, description)

                Case "LuEmployeeServiceType"

                    Return Cdm.DataCore.LookupTables.LuEmployeeServiceType.Exists(id, description)

                Case "LuEmployeeAuthentication"

                    Return Cdm.DataCore.LookupTables.LuEmployeeAuthentication.Exists(id, description)

                Case "LuEmployeeType"

                    Return Cdm.DataCore.LookupTables.LuEmployeeType.Exists(id, description)

                Case "LuGeographicLocation"

                    Return Cdm.DataCore.LookupTables.LuGeographicLocation.Exists(id, description)

                Case "LuLegalGuardianType"

                    Return Cdm.DataCore.LookupTables.LuLegalGuardianType.Exists(id, description)

                Case "LuSourceOfEnrollment"

                    Return Cdm.DataCore.LookupTables.LuSourceOfEnrollment.Exists(id, description)

                Case "LuGender"

                    Return Cdm.DataCore.LookupTables.LuGender.Exists(id, description)

                Case "LuStatePlanOption"

                    Return Cdm.DataCore.LookupTables.LuStatePlanOption.Exists(id, description)

                Case "LuCounty"

                    Return Cdm.DataCore.LookupTables.LuCounty.Exists(id, description)

                Case "LuRace"

                    Return Cdm.DataCore.LookupTables.LuRace.Exists(id, description)

            End Select

        Catch ex As Exception
            Cdm.AppServices.Log.ErrorLog("LookupTables", "An error occurred in the Exists() method", ex)
            Throw ex
        End Try

    End Function

    Private Sub CheckMatch(ByVal sproc As String)

        Dim sDataSourceTN As String
        Dim sDataSourceDOTN As String
        Dim sDropDownVal As String
        message = ""
        sDataSourceTN = Me.LookupTablesObjectDataSource.TypeName
        sDataSourceDOTN = Me.LookupTablesObjectDataSource.DataObjectTypeName
        sDropDownVal = Me.LuTablesDropDownList.SelectedValue
        If Not (sDataSourceDOTN.Equals(sDropDownVal)) Then
            message = "Object is " & sDataSourceDOTN & "; dropdown is " & sDropDownVal
        End If
        If Not (sDataSourceDOTN.Equals(sDataSourceTN)) Then
            message = message & "    " & "Object is " & sDataSourceDOTN & "; typename is " & sDataSourceTN
        End If
        If Not (sDataSourceDOTN.Equals(sDataSourceTN)) Then
            message = message & "    " & "Object is " & sDataSourceDOTN & "; typename is " & sDataSourceTN
        End If
        If Not (message.Equals("")) Then
            message = message & " ! from " & sproc
        End If

    End Sub

    Protected Sub NewDetailsView_ItemInserted(ByVal sender As Object, _
                                     ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) _
                                     Handles NewDetailsView.ItemInserted

        Me.LookupTablesObjectDataSource.Select()
        Me.LookupTablesScrollingGridView.DataBind()

    End Sub

    Protected Sub AddButton_Click(ByVal sender As Object, _
                                ByVal e As System.EventArgs) _
                                Handles AddButton.Click

        SetGridViewPanelVisible(False)

        Me.AddButton.Visible = False
        'Me.SubtitleLabel.Visible = False
        Me.ErrorSummary.Visible = False

        Me.NewDetailsView.Visible = True
        Me.SubmitButton.Visible = True
        Me.CancelButton.Visible = True

    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, _
                                ByVal e As System.EventArgs) _
                                Handles SubmitButton.Click

        Dim lookupTableName As String = Me.LuTablesDropDownList.SelectedValue.Substring(Me.LuTablesDropDownList.SelectedValue.LastIndexOf(".") + 1)
        Dim field As TextBox = CType(Me.NewDetailsView.Rows(0).Cells(1).Controls(0), TextBox)

        'CHECK TO SEE IF THE DESCRIPTION ALREADY EXISTS IN THE TABLE
        If Me.Exists(lookupTableName, field.Text.Trim(), 0) Then
            Me.ErrorSummary.SetSingleError("An item with this description already exists. Please enter a different value.")
            Me.ErrorSummary.Visible = True
            Exit Sub
        End If

        Me.NewDetailsView.InsertItem(False)

        If success = 1 Then
            Me.ErrorSummary.Visible = False
            Me.NewDetailsView.Visible = False

            Me.SubmitButton.Visible = False
            Me.CancelButton.Visible = False
            SetGridViewPanelVisible(True)


            Me.AddButton.Visible = True
            CType(Me.NewDetailsView.Rows(0).Cells(1).Controls(0), TextBox).Text = ""
            SetStatus("New item has been added.")
        Else
            'Me.LookupTablesGridView.Visible = False
            Me.AddButton.Visible = False
            SetGridViewPanelVisible(False)
            Me.NewDetailsView.Visible = True

            Me.SubmitButton.Visible = True
            Me.CancelButton.Visible = True
        End If

    End Sub

    Protected Sub CancelButton_Click(ByVal sender As Object, _
                                ByVal e As System.EventArgs) _
                                Handles CancelButton.Click
        SetGridViewPanelVisible(True)
        Me.NewDetailsView.Visible = False
        Me.SubmitButton.Visible = False
        Me.CancelButton.Visible = False
        Me.ErrorSummary.Visible = False
        Me.AddButton.Visible = True
        CType(Me.NewDetailsView.Rows(0).Cells(1).Controls(0), TextBox).Text = ""
        SetStatus("Insert Cancelled.")
    End Sub

    Protected Sub NewDetailsView_ItemInserting(ByVal sender As Object, _
                                      ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) _
                                      Handles NewDetailsView.ItemInserting

        For i As Integer = 0 To e.Values.Count - 1

            If e.Values(i) Is Nothing Then  'Blank field check

                value = Me.NewDetailsView.Rows(0).Cells(0).Text & " must be filled in before proceeding."
                Me.ErrorSummary.SetSingleError(value)
                e.Cancel = True
                Me.ErrorSummary.Visible = True
                success = 0
                Exit Sub

            Else

                Dim existingDescription As String
                Dim newDescription As String = e.Values(i).ToString
                'If there is existing data check for duplicate record
                If LookupTablesScrollingGridView.Rows.Count > 0 Then

                    For j As Integer = 0 To LookupTablesScrollingGridView.Rows.Count - 1

                        existingDescription = CType(Me.LookupTablesScrollingGridView.Rows(j).Cells(0).Controls(0), DataBoundLiteralControl).Text

                        If newDescription.ToLower = existingDescription.ToLower Then
                            value = "Value already exists in the database. Please enter a different value."
                            Me.ErrorSummary.SetSingleError(value)
                            e.Cancel = True
                            Me.ErrorSummary.Visible = True
                            success = 0
                            Exit Sub
                        Else
                            e.Values(i) = Server.HtmlEncode(e.Values(i).ToString())
                            success = 1
                        End If

                    Next

                Else
                    success = 1
                End If

            End If

        Next

    End Sub

    Protected Sub LookupTablesScrollingGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles LookupTablesScrollingGridView.RowCancelingEdit
        If ErrorSummary.Visible = True Then
            ErrorSummary.Visible = False
            SetGridViewPanelVisible(True)
        End If
        Me.AddButton.Visible = True
        SetStatus("Edit Cancelled")
    End Sub

    Protected Sub LookupTablesScrollingGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles LookupTablesScrollingGridView.RowCommand
        Me.ErrorSummary.Visible = False

        If e.CommandName = "DeleteListItem" Then

            Dim lookupTableType As String = Me.LuTablesDropDownList.SelectedValue
            Me.DoDelete(lookupTableType.Substring(lookupTableType.LastIndexOf(".") + 1), e.CommandArgument)

        End If

        Me.LookupTablesObjectDataSource.TypeName = C_TABLE_NAMESPACE & Me.LuTablesDropDownList.SelectedValue
        Me.LookupTablesObjectDataSource.DataObjectTypeName = C_TABLE_NAMESPACE & Me.LuTablesDropDownList.SelectedValue
        Me.LookupTablesScrollingGridView.DataBind()
    End Sub

    Protected Sub LookupTablesScrollingGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles LookupTablesScrollingGridView.RowDataBound
        If e.Row.DataItemIndex = 0 Then
            AccessibilityController.AddImageToSortableGridHeaders(LookupTablesScrollingGridView)
        End If
        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim deleteButton As LinkButton = CType(e.Row.Cells(2).Controls(1), LinkButton)
            deleteButton.CommandArgument = Me.LookupTablesScrollingGridView.DataKeys(e.Row.RowIndex).Values(0)

            Dim txtDescription As TextBox = CType(e.Row.FindControl("txtDescription"), TextBox)
            If Not txtDescription Is Nothing Then
                SetFocus(txtDescription.ClientID)
            End If

        End If
    End Sub

    Protected Sub LookupTablesScrollingGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles LookupTablesScrollingGridView.RowEditing
        Me.AddButton.Visible = False
    End Sub

    Protected Sub LookupTablesScrollingGridView_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles LookupTablesScrollingGridView.RowUpdated
        Me.AddButton.Visible = True
        SetStatus("Row updated.")
    End Sub

    Protected Sub LookupTablesScrollingGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles LookupTablesScrollingGridView.RowUpdating
        Dim strNV As String
        Dim strOV As String = e.OldValues.Item(index).ToString.ToUpper
        Dim lookupTableName As String
        Dim itemId As Integer

        If e.NewValues.Item(index) IsNot Nothing Then
            strNV = e.NewValues.Item(index).ToString.ToUpper.Trim()
            If strOV = strNV Then
                e.Cancel = True
                Me.AddButton.Visible = True

                If Me.ErrorSummary.Visible = True Then
                    Me.ErrorSummary.Visible = False
                End If
            Else

                lookupTableName = Me.LuTablesDropDownList.SelectedValue.Substring(Me.LuTablesDropDownList.SelectedValue.LastIndexOf(".") + 1)
                itemId = CType(e.Keys(0), Integer)

                'CHECK TO SEE IF THE DESCRIPTION ALREADY EXISTS IN THE TABLE
                If Me.Exists(lookupTableName, strNV, itemId) Then
                    Me.ErrorSummary.SetSingleError("An item with this description already exists. Please enter a different value.")
                    Me.ErrorSummary.Visible = True
                    Me.AddButton.Visible = True
                    e.Cancel = True
                    Exit Sub
                End If

                Me.ErrorSummary.Visible = False
                e.NewValues.Item(index) = Server.HtmlEncode(e.NewValues.Item(index).ToString())
            End If
        Else
            value = "You must enter a value in the field before updating."
            Me.ErrorSummary.SetSingleError(value)
            Me.ErrorSummary.Visible = True
            e.Cancel = True
        End If

    End Sub
End Class
